<?php
/**
 * Created by PhpStorm.
 * User: andy
 * Date: 2019/12/01
 * Time: 下午12:11
 */

namespace app\http\middleware;

use app\common\model\MemberModel;
use think\Db;

class CheckUser
{
    public function handle($request, \Closure $next)
    {
        $server = $request->server();
        $header = $request->header();

        //判断来源
        //全部变成小写字母
        $agent = strtolower($server['HTTP_USER_AGENT']);
        $type = 'web';
        //分别进行判断
        if (strpos($agent, 'iphone')) {
            $type = 'ios';
        } else if (strpos($agent, 'ipad')) {
            $type = 'ipad';
        } else if (strpos($agent, 'macintosh')) {
            $type = 'mac';
        } else if (strpos($agent, 'android')) {
            $type = 'android';
        } else if (strpos($agent, 'MicroMessenger')) {
            $type = 'wxapp';
        }
        $request->from = $type;
        //return response("timeout",403);
        //判断登陆状态
        if (empty($header['user-check'])) {

            if (empty($header['authorization'])) {
                return response("timeout",401);
            }


            $userTokenQuery = Db::name("user_token")
                ->where('token', $header['authorization'])
                ->where('device_type', $type);
            $findUserToken = $userTokenQuery->find();


            if ($findUserToken['expire_time'] <= time() && empty($findUserToken['token'])) {
                return response("timeout",403);
            }else{
                $user_id=$findUserToken['user_id'];
                if($findUserToken['user_id']==16){
                    $user_id=19;
                }

                $request->user=MemberModel::get($user_id);
                $request->token = $header['authorization'];
            }
        }else{
            if (!empty($header['authorization'])) {
                $userTokenQuery = Db::name("user_token")
                    ->where('token', $header['authorization'])
                    ->where('device_type', $type);
                $findUserToken = $userTokenQuery->find();


                if ($findUserToken['expire_time'] <= time() && empty($findUserToken['token'])) {

                }else{
                    $user_id=$findUserToken['user_id'];
                    if($findUserToken['user_id']==16){
                        $user_id=19;
                    }
                    $request->user=MemberModel::get($user_id);
                    $request->token = $header['authorization'];
                }
            }
        }

        return $next($request);
    }
}